from django.core.paginator import Paginator
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import StudyRecord
from .serializers import StudyRecordSerializer
from django.db.models import Sum, Count
from django.utils import timezone
from datetime import timedelta


class StudyRecordView(APIView):
    """学习记录视图"""
    permission_classes = []

    def get(self, request):
        try:
            # 读取查询参数
            user_id = request.GET.get('user_id')  # '' / None / '3'
            category = request.GET.get('category')  # primary / senior ...
            start_date = request.GET.get('start_date')  # '2025-05-01'
            end_date = request.GET.get('end_date')  # '2025-05-08'
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))

            # 构建 QuerySet
            qs = StudyRecord.objects.all().select_related('user')

            if user_id:  # 只有传了才过滤
                qs = qs.filter(user_id=user_id)
            if category:
                qs = qs.filter(category=category)
            if start_date and end_date:
                qs = qs.filter(start_time__date__range=[start_date, end_date])

            # 分页
            paginator = Paginator(qs, page_size)
            page_obj = paginator.get_page(page)

            serializer = StudyRecordSerializer(page_obj, many=True)

            return Response({
                'results': serializer.data,
                'total': paginator.count,
                'page': page,
                'page_size': page_size
            })
        except Exception as e:
            return Response({'error': str(e)},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, request):
        """创建学习记录"""
        try:
            serializer = StudyRecordSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def delete(self, request, record_id):
        """删除学习记录"""
        try:
            record = StudyRecord.objects.get(id=record_id)
            record.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except StudyRecord.DoesNotExist:
            return Response(
                {'error': '记录不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class StudyStatisticsView(APIView):
    """学习统计视图"""
    permission_classes = []

    def get(self, request):
        """获取学习统计数据"""
        try:
            user_id = request.GET.get('user_id')
            today = timezone.now().date()

            # 今日统计
            today_stats = StudyRecord.objects.filter(
                user_id=user_id,
                start_time__date=today
            ).aggregate(
                total_duration=Sum('duration'),
                session_count=Count('id')
            )

            # 本周统计
            week_start = today - timedelta(days=today.weekday())
            week_stats = StudyRecord.objects.filter(
                user_id=user_id,
                start_time__date__gte=week_start
            ).aggregate(
                total_duration=Sum('duration'),
                session_count=Count('id')
            )

            return Response({
                'today': {
                    'total_duration': today_stats['total_duration'] or 0,
                    'session_count': today_stats['session_count'] or 0
                },
                'week': {
                    'total_duration': week_stats['total_duration'] or 0,
                    'session_count': week_stats['session_count'] or 0
                }
            })
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
